import { defineStore } from "pinia";
import requests from "../utils/requests";
import { jwtDecode } from "jwt-decode";

const useloginStore=defineStore('login',{
	state:()=>({
		form:{
			username:'',
			password:''
		}
	}),
	actions:{
		async login(){
			const res=await requests({
				url:'/base/login/',
				method:"post",
				data:{
					username:this.form.username,
					password:this.form.password
				}
			})
			if(res.code===200){
				uni.$u.toast('登录成功')
				uni.setStorageSync('token', res.data);
				const decode_token=jwtDecode(res.data)
				uni.setStorageSync('username',decode_token.username)
				uni.setStorageSync('role',JSON.stringify(decode_token.role))
				uni.setStorageSync('email',decode_token.email)
				uni.setStorageSync('phone',decode_token.phone)
				uni.setStorageSync('exp',JSON.stringify(decode_token.exp))
				uni.switchTab({
					url:'/pages/home/home'
				})
				this.form.username='',
				this.form.password=''
			}else{
				uni.$u.toast(`登陆失败，${res.error}`)
			}
		},
		register(){
			uni.navigateTo({
				url:'/pages/register/register',
				animationType: 'pop-in',
				animationDuration: 1000
			})
		},
		pwd(){
			uni.navigateTo({
				url:'/pages/pwd/pwd',
				animationType: 'pop-in',
				animationDuration: 1000
			})
		},
		hospital(){
			uni.setStorageSync('hospital_latitude',29.510171)
			uni.setStorageSync('hospital_longitude',105.773445)
		}
	}
})
export default useloginStore;